package gl.vbm

import gl.util.string
import gl.util.unsignedInt
import java.nio.ByteBuffer

class VBMHeader(buffer: ByteBuffer) {
    val magic: Int // uint
    val size: Int // uint
    val name: String
    val attribCount: Int // uint
    val frameCount: Int // uint
    val chunkCount: Int // uint
    val vertexCount: Int // uint
    val indexCount: Int // uint
    val indexType: Int // uint
    val materialCount: Int // uint
    val flags: Int // uint

    val nameArray: ByteArray
    val beginPosition: Int
    val endPosition: Int
    val isOld: Boolean

    private fun readUnsignedIntLimited(buffer: ByteBuffer): Int {
        return if (buffer.position() < endPosition) {
            buffer.unsignedInt.toInt()
        } else 0
    }

    init {
        beginPosition = buffer.position()
        magic = buffer.int
        isOld = magic != 0x314d4253
        size = buffer.unsignedInt.toInt()
        endPosition = beginPosition + size
        buffer[ByteArray(64).also { nameArray = it }]
        attribCount = readUnsignedIntLimited(buffer)
        frameCount = readUnsignedIntLimited(buffer)
        chunkCount = if (isOld) readUnsignedIntLimited(buffer) else 0
        vertexCount = readUnsignedIntLimited(buffer)
        indexCount = readUnsignedIntLimited(buffer)
        indexType = readUnsignedIntLimited(buffer)
        materialCount = readUnsignedIntLimited(buffer)
        flags = readUnsignedIntLimited(buffer)
        name = nameArray.string()
    }
}